from rest_framework import serializers
from rest_framework.response import Response
from . import models
import time
from rest_framework_jwt.serializers import jwt_payload_handler, jwt_encode_handler
import re


class RegisterSer(serializers.ModelSerializer):
    mobile = serializers.CharField(max_length=16,write_only=True)
    password = serializers.CharField(max_length=16,write_only=True)

    class Meta:
        model = models.User
        fields = ['mobile','password']

    def validate(self, attrs):
        mobile = attrs.get('mobile')
        if not (mobile and re.match(r'^1[3-9][0-9]{9}$', mobile)):
            raise serializers.ValidationError({
                'status': 100,
                'msg': '手机号有误'
            })
        user = models.User.objects.filter(mobile=mobile)
        if user:
            raise serializers.ValidationError({
                'status': 100,
                'msg': '手机号已经注册了'
            })

        username = str(mobile)
        attrs['username'] = username
        self.attrs = attrs
        return attrs

class LoginSer(serializers.ModelSerializer):
    mobile = serializers.CharField(max_length=16)
    password = serializers.CharField(max_length=16)
    class Meta:
        model = models.User
        fields = ['mobile','password']

    def validate(self, attrs):
        username = attrs.get('mobile')
        password = attrs.get('password')
        user_obj = models.User.objects.filter(username=username).first()
        if not user_obj:
            return Response(data={
                'status': 100,
                'msg': '手机号未注册'
            }, status=400)
        is_right = user_obj.check_password(password)
        if is_right:
            user_obj.user = user_obj
            self.username = username
        else:
            raise serializers.ValidationError({
                'status': 100,
                'msg': '密码错误'
            })
        return attrs


class OrderSer(serializers.ModelSerializer):
    class Meta:
        model = models.Order
        fields = [
            'subject',
            'total_amount',
            'name'
        ]
        extra_kwargs = {
            'total_amount': {
                'required': True
            },
            'name': {
                'required' : True
            }
        }

    def validate(self, attrs):
        subject = attrs.get('subject')
        total_amount = attrs.get('total_amount')
        attrs['out_trade_no']  = str(time.time())[0:10]
        attrs['order_status']  = 1
        # attrs['pay_time'] =time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
        # self.attrs = attrs
        return attrs

class OrderListSer(serializers.ModelSerializer):
    class Meta:
        model = models.Order

        fields = [
            'order_type',
            'pk',
            'subject',
            'out_trade_no',
            'pay_time',
            'total_amount',
            'name',
        ]